﻿//-----------------------------------------------------------------------
// <copyright file="Singleton.cs" company="CodePlex">
//     Copyright (c) Doug Holland, CodePlex. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace CodePlex.DesignPatterns
{
    using System;

    /// <summary>
    /// Provides a template for the Singleton design pattern implemented within the C# programming language.
    /// </summary>
    /// <remarks>
    /// <para>
    /// Given that the constructor for the <see cref="T:Singleton"/> class is private, an instance of the class can
    /// only be created from within the class declaration itself. Therefore the <see cref="T:Singleton"/> class 
    /// contains a static instance field of type <see cref="T:Singleton"/> and a static read only property that returns
    /// the unique instance. Unlike the previous example that checks if the unique instance is null within the
    /// <see cref="M:Singleton.UniqueInstance"/> property this example uses a static type initializer to create the
    /// unique instance of the <see cref="T:Singleton"/> class.
    /// </para>
    /// <para>
    /// It should be noted however that the <see cref="T:Singleton"/> design pattern, when implemented within the .net
    /// platform, only ensures that the instance is unique within the given application domain. If an instance needs to
    /// be unique across multiple application domains then it will be necessary to write some unmanaged code to enforce
    /// that restriction.
    /// </para>
    /// </remarks>
    public sealed class Singleton
    {
        #region Singleton Private Fields

        /// <summary>
        /// Unique instance of the <see cref="T:Singleton"/> class.
        /// </summary>
        private static Singleton instance;

        #endregion

        #region static Singleton()

        /// <summary>
        /// Initializes the <see cref="T:Singleton"/> class.    
        /// </summary>
        static Singleton()
        {
            // create the unique instance of the Singleton class.
            instance = new Singleton();
        }

        #endregion

        #region private Singleton()

        /// <summary>
        /// Prevents a default instance of the <see cref="T:Singleton"/> class from being created.
        /// </summary>
        private Singleton()
        {
        }

        #endregion

        #region public static Singleton UniqueInstance()

        /// <summary>
        /// Gets the unique instance of the <see cref="T:Singleton"/> class.
        /// </summary>
        /// <returns>The unique instance of the <see cref="T:Singleton"/> class.</returns>
        public static Singleton UniqueInstance
        {
            get
            {
                return instance;
            }
        }

        #endregion
    }
}
